import logging
from logging.handlers import TimedRotatingFileHandler

from example.globals import app_config


def setup_logger(level: str, filename: str, keep_days: int):
    # 创建或获取全局 logger（命名为 "GlobalLogger"）
    logger = logging.getLogger("GlobalLogger")
    logger.setLevel(logging.getLevelName(level.upper()))  # 设置日志级别

    # 避免重复添加 Handler（防止多次调用 setup_logger 时重复配置）
    if not logger.handlers:
        # 定义日志格式
        formatter = logging.Formatter(
            "%(asctime)s - %(module)s - %(levelname)s - %(message)s",  # 显示模块名
            datefmt="%Y-%m-%d %H:%M:%S"
        )

        # 创建按天切割的 FileHandler
        file_handler = TimedRotatingFileHandler(
            filename=filename,
            when="midnight",
            interval=1,
            backupCount=keep_days,
            encoding="utf-8"
        )
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

        # 可选：添加控制台 Handler
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    return logger
